//
//  CoreDataManager.m
//  CoreData通讯录
//
//  Created by 邝子涵 on 15/11/20.
//  Copyright © 2015年 kuangzihan. All rights reserved.
//

#import "CoreDataManager.h"
#define ENTITY_NAME @"Student"
@implementation CoreDataManager

+ (CoreDataManager *)defaults{
    static CoreDataManager *manger;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [[CoreDataManager alloc] init];
    });
    return manger;
}



#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;



- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.kuangzihan.CoreData___" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreData___" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData___.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support
- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not NSEntityDescriptionuse this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - 添加联系人方法
- (Student *)addDataAddressBook:(NSString *)name phone:(NSString *)phone sex:(NSString *)sex number:(NSNumber *)number QQ:(NSString *)qq nativePlace:(NSString *)nativePlace{
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:self.managedObjectContext];
    
    Student *student = [[Student alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
    
    student.name = name;
    student.sex = sex;
    student.phone = phone;
    student.number = number;
    student.qq = qq;
    student.nativeplace = nativePlace;
    
    [self saveContext];
    
    return student;
}

#pragma mark - 查询方法
- (NSArray *)slect{
    // 获取查询数据的请求, 相当于数据库里的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:ENTITY_NAME];
    
    NSError *error;
    // 查找到的数组对象, 通过一个数组显示出来
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    
    return array;
}

#pragma mark - 删除联系人
- (void)deleteName:(NSString *)name{
    
    // 获取查询数据的请求,相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:ENTITY_NAME];
    // 增加约束
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], name];
    request.predicate = predicate;
    
    // 通过某个key给数组排序
//    NSSortDescriptor *sortDesriotor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
//    // 排序
//    [request setSortDescriptors:[NSArray arrayWithObjects:sortDesriotor, nil]];
//    
    // 赋值重要一步
    NSError *error;
    NSArray *arr = [self slect];
    arr = [self.managedObjectContext executeFetchRequest:request error:&error];
    
    // 删除数据内容
    for (Student *stu in arr) {
        [self.managedObjectContext deleteObject:stu];
        NSLog(@"删除: =====%@", stu.name);
    }
    
    // 保存
    [self saveContext];
}

#pragma mark - 修改联系人
- (Student *)reviseAddressBook:(NSString *)name phone:(NSString *)phone sex:(NSString *)sex number:(NSNumber *)number QQ:(NSString *)qq nativePlace:(NSString *)nativePlace{
    // 获取查询数据请求,相当于数据库中的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:ENTITY_NAME];
    // 增加约束
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], name];
    request.predicate = predicate;
    
    // 赋值重要一步
    NSError *error;
    NSArray *arr = [self.managedObjectContext executeFetchRequest:request error:&error];
    
    // 因对应其名字的只有一个数据,获取最后就是获取当前的
    Student *studet = [arr lastObject];
    
    studet.name = name;
    studet.phone = phone;
    studet.sex = sex;
    studet.number = number;
    studet.qq = qq;
    studet.nativeplace = nativePlace;
    
    // 保存
    [self saveContext];
    
    return studet;
}

@end